class Category < ActiveRecord::Base

  acts_as_nested_set :dependent => :destroy

  before_save :make_permalink
  
  belongs_to :category_group, :touch => true

  has_and_belongs_to_many :products, :join_table => "product_has_categories"

  has_one :icon, :as => :viewable, :order => :position, :dependent => :destroy

  scope :active, :conditions => "hidden = 0"
  
  validates :presentation, :length => {:maximum => 30}, :presence => true
  validates :headline, :length => {:maximum => 60}, :presence => true
  validates :title, :length => {:maximum => 250}, :presence => true
  validates :url, :length => {:maximum => 30}, :format => {:with => Format::URL_REGEX}, :presence => true
  validates :permalink, :length => {:maximum => 100}, :uniqueness => true

  accepts_nested_attributes_for :icon, :allow_destroy => true#, :reject_if => proc {|attr| attr['attachment_file_name'].blank?}

  has_paper_trail :ignore => [:id, :lft, :rgt, :level, :permalink, :parent_id]
  diff :exclude => [:lft, :rgt, :level, :permalink, :updated_at, :created_at]

  def make_permalink
    if self.parent_id.blank?
      self.permalink = self.category_group.root_url + self.url + "/"
    else
      self.permalink = Category.find(self.parent_id).permalink + self.url + "/"
    end

    unless self.children.blank?
      self.children.each do |category|
        category.make_permalink
        category.save
      end
    end
  end

#  alias new_photo photo
#  def photo
#    new_photo || build_photo
#  end
end
